package cn.qingfeng.a003_chat_v2_1.server.handler;

import cn.qingfeng.a003_chat_v2_1.message.ChatRequestMessage;
import cn.qingfeng.a003_chat_v2_1.message.ChatResponseMessage;
import cn.qingfeng.a003_chat_v2_1.server.session.Session;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class SendHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage message) throws Exception {
        try {
            if (message == null) {
                return;
            }
            String fromUsername = message.getFromUsername();
            String toUsername = message.getToUsername();
            String content = message.getContent();
            Channel toChannel = Session.getChannel(toUsername);
            toChannel.writeAndFlush(new ChatResponseMessage("send2", true, fromUsername, toUsername, content));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}